/*
 * @Description: 菜单管理模块
 * @Author: zhihong deng
 * @Date: 2021-09-17 21:38:03
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-09-20 19:00:28
 */
const router = require('koa-router')()
const util = require('../utils/util')
const Menu = require('../models/menuSchema')
router.prefix('/menu') // 路由前缀

// 菜单列表
router.get('/list', async (ctx) => {
	const { menuName, menuState } = ctx.request.query
	const params = {}
	if (menuName) params.menuName = menuName
	if (menuState) params.menuState = menuState
	let rootList = (await Menu.find(params)) || []
	const permissionList = util.getTreeMenu(rootList, null, [])
	ctx.body = util.success(permissionList)
})


// 菜单创建/编辑/删除
router.post('/operate', async (ctx) => {
	const { _id, action, ...params } = ctx.request.body
	let res, info
	try {
		if (action == 'add') {
			res = await Menu.create(params)
			info = '创建成功'
		} else if (action == 'edit') {
			params.updateTime = new Date()
			res = await Menu.findByIdAndUpdate(_id, params)
			info = '编辑成功'
		} else {
			res = await Menu.findOneAndRemove(_id)
			// 删除父级时，父级id下的子级也被删除
			await Menu.deleteMany({ parentId: { $all: [_id] } })
			info = '删除成功'
		}
		ctx.body = util.success('', info)
	} catch (error) {
		ctx.body = util.fail(error.stack)
	}
})
module.exports = router
